#include <cstring>
#include <cctype>
#include <stack>
using std::stack;

#include "Function.h"

stack<NodeType> st;

double readNumber(char *str, int &pos, int len) {
    double ret = 0;
    bool decimalFlag = false;
    double decimalEps = 1;
    while (pos <= len && (isdigit(str[pos]) || str[pos] == '.')) {
        if (str[pos] == '.') {
            decimalFlag = true;
        } else if (!decimalFlag) {
            ret = ret * 10 + str[pos] - '0';
        } else {
            decimalEps *= 0.1;
            ret += decimalEps * (str[pos] - '0');
        }
        ++ pos;
    }
    return ret;
}

void newNode(ParseResultNode *cur, ParseResultNode *last, double value, NodeType type) {
    cur->value = value;
    cur->type = type;
    cur->next = new ParseResultNode();
    last = cur;
    cur = cur->next;
}

/**
 *  解析字符串为逆波兰表达式
 *  失败返回null 
*/
ParseResultNode* parse(char *str) {
    int len = strlen(str);
    while (!st.empty()) st.pop();
    ParseResultNode *head = new ParseResultNode(), *cur = head, *last = NULL;
    for (int i = 0; i < len; i ++) {
        if (isdigit(str[i])) {
            newNode(cur, last, readNumber(str, i, len), CONSTANT);
        } else {
            switch (str[i])
            { // TODO 
            case '+': // plus
                break;
            case '-':
                break;
            case '*':
                break;
            case '/':
                break;
            case '(':
                break;
            case ')':
                break;
            case 'c': // cos
                break;
            case 's': // sin sqrt
                break;
            case 't': // tan
                break;
            case 'a': // arccos arcsin arctan
                break;
            case 'log': // log log2 log10
                break;
            case 'x': // x
                newNode(cur, last, 0, X);
                break;
            default:
                return NULL;
            }
        }
    }
    last->next = NULL;
    return head;
}